package 卖票;

public class SellTickets implements Runnable {
    private  static int ticket = 100;
    private Object obj = new Object();
    int i =0;
    //对应对象为this
    public synchronized void sell (){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "卖出第："+ticket+"张票");
            ticket--;
            System.out.println("已售出");
    }
    //对应对象为xxx.class
    public static synchronized void sell2 (){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "卖出第："+ticket+"张票");
        ticket--;
        System.out.println("已售出");
    }

    @Override
    public void run() {
        if (i %2==0){
        while (true) {
            synchronized (this){
            if (ticket > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖出第："+ticket+"张票");
                ticket--;
                System.out.println("已售出");
            }else{
            sell();
            }
        }
    }
}}}